<template>
    <el-dialog
        title="设置"
        :visible.sync="show"
        @close="$emit('close')"
        width="500px"
        :before-close="clearModel"
    >
    <div>
        <el-form
        label-width="80px" 
        :model="update"
        ref="updateModel"
        >
            <el-form-item label="新名称">
                <el-input 
                v-model="update.username"
                placeholder="输入新名称"></el-input>
            </el-form-item>
            <el-form-item label="新密码">
                <el-input 
                v-model="update.passwd"
                placeholder="输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="新头像">
                <el-upload
                name="image"
                class="avatar-uploader"
                :action="`${this.$API}/upload-avatar`"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="update.avatar" :src="$API+update.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item 
            label="公钥"
            prop="publicKey"
            :rules="[
                { validator: keyPairTest }
            ]"
            >
                <div
                    @drop.stop.prevent="fileRead('public', $event)"
                >
                    <el-input 
                    v-model="update.publicKey"
                    :validate-event="false"
                    type="textarea"
                    :rows="2"
                    placeholder="上传公钥，使用pem格式，可拖动文件添加。"
                    resize="none"
                    />
                </div>
            </el-form-item>
            <el-form-item label="私钥">
                <div
                @drop.stop.prevent="fileRead('private', $event)"
                >
                    <el-input 
                    v-model="privateKey"
                    :validate-event="false"
                    type="textarea"
                    :rows="2"
                    placeholder="上传私钥，使用pem格式，可拖动文件添加。"
                    resize="none"
                    />
                </div>
            </el-form-item>
        </el-form>
    </div>
    <div slot="footer">
        <el-button type="danger" @click="remove">退出登录</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
    </div>
    </el-dialog>
</template>

<script>
import { EncryptRsa, DecryptRsa } from '../utils/crypto'
import axios from 'axios'

export default {
    name: 'setting',
    props: {
        show: {
            default: true,
            type: Boolean,
        },
    },

    data() {
        return {
            update: {
                username: '',
                userid: '',
                token: '',
                avatar: '',
                passwd: '',
                publicKey: '',
            },
            privateKey: ''
        }
    },
    methods: {
        remove() {
            window.localStorage.removeItem('chat-user');
            location.reload()
        },
        clearModel(done) {
            this.update = {
                username: '',
                userid: '',
                token: '',
                avatar: '',
                passwd: '',
                publicKey: '',
            }
            done()
        },

        fileRead(target, e) {
            const file = e.dataTransfer.files[0];
            const fileType = /\.pem/
            if (!fileType.test(file.name)) {
                this.$message.error('密钥必须是pem格式')
                return
            }
            const reader = new FileReader();
            reader.onload = evt => {
                if (target == 'public') {
                    this.update.publicKey = evt.target.result;
                } else {
                    this.privateKey = evt.target.result;
                }
            }
            reader.readAsText(file)
        },
        keyPairTest(rule, value, callback) {
            const publicKey = this.update.publicKey;
            const privateKey = this.privateKey;
            if (privateKey&&!publicKey) {
                callback(new Error('未设置公钥'))
                // return
            }
            if (!privateKey&&publicKey) {
                callback(new Error('未设置私钥'))
                // return
            }
            if (privateKey&&publicKey) {
                try {
                    const originMsg = 'ok';
                    const encode = EncryptRsa(originMsg, publicKey);
                    const decode = DecryptRsa(encode, privateKey);
                    if (originMsg!=decode) {
                        callback(new Error('密钥对无法通过测试'))
                        // return
                    }
                    callback()
                }
                catch(e){
                    callback(new Error('密钥对无法通过测试'))
                }
                // return
            }
            callback()
        },
        submit() {
            this.$refs['updateModel'].validate(val => {
                if (val) {
                    const {
                        username,
                        avatar,
                        passwd,
                        publicKey,
                    } = this.update
                    const chatuser = JSON.parse(window.localStorage.getItem('chat-user'))
                    const { userid, token } = chatuser
                    axios.post(`${this.$API}/updateUser`, {
                        username,
                        avatar,
                        passwd,
                        publicKey,
                        userid, token
                    }).then(res => {
                        if (res.data.code === 200) {
                            let info = {
                                avatar: res.data.data.avatar,
                                publicKey: res.data.data.publicKey,
                                token: res.data.data.token,
                                userid: res.data.data.userid,
                                username: res.data.data.username
                            }
                            this.$_.$emit('update user', info)
                            window.localStorage.setItem('chat-user', JSON.stringify(info))
                            if (publicKey) {
                                const privateKey = this.privateKey;
                                window.localStorage.setItem(`PRIVATE_${userid}`, privateKey);
                            }
                            this.$emit('close')
                        }
                    })
                }
            })
        },
        handleAvatarSuccess(res, file) {
            this.update.avatar = `/avatar/${res.file}`;
        },
        beforeAvatarUpload(file) {
            const isJPG = ['image/jpeg','image/png'].includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 1;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>

<style scoped>
 /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
/deep/.el-textarea__inner {
    height: auto !important;
}
</style>